<template>
  <div class="chat-wrapper">
    <!-- 导航栏 -->
    <van-nav-bar
      :title="caseInfo.caseName || '案件详情'"
      left-text="返回"
      left-arrow
      @click-left="goBack"
      fixed
    />
    
    <!-- 案件信息卡片 -->
    <div class="content-wrapper">
      <van-cell-group inset class="case-info-card" v-if="caseInfo">
        <van-cell title="案件名称" :value="caseInfo.caseName" />
        <van-cell title="案件程序" :value="caseInfo.caseProcedure" />
        <van-cell title="分析状态">
          <van-tag :type="getStatusTagType(caseInfo.analysisStatus)">
            {{ caseInfo.analysisStatus }}
          </van-tag>
        </van-cell>
        <van-cell title="胜率预测">
          <van-progress 
            :percentage="caseInfo.victoryRate" 
            :color="getVictoryRateColor(caseInfo.victoryRate)"
            stroke-width="8"
            :show-pivot="false"
          />
          <span class="victory-rate-text">{{ caseInfo.victoryRate }}%</span>
        </van-cell>
      </van-cell-group>

      <!-- 聊天内容区域 -->
      <div class="chat-container">
        <div class="chat-content" ref="chatContent">
          <div 
            v-for="(msg, index) in messages" 
            :key="index" 
            class="message" 
            :class="msg.role"
          >
            <div class="message-bubble">
              <div class="message-header">
                <van-icon v-if="msg.role === 'user'" name="user-circle-o" size="16" />
                <van-image v-else round width="24" height="24" class="avatar" :src="aiAvatar" />
                <span class="sender-name">{{ msg.role === 'user' ? '您' : 'AI小诺' }}</span>
                <span class="message-time">{{ formatMessageTime(msg) }}</span>
              </div>
              <div class="message-text" v-html="msg.renderedText || msg.content"></div>
            </div>
          </div>

          <!-- 流式响应时的加载指示器 -->
          <div v-if="isStreaming" class="message ai">
            <div class="message-bubble">
              <div class="message-header">
                <van-image round width="24" height="24" class="avatar" :src="aiAvatar" />
                <span class="sender-name">AI小诺</span>
                <span class="message-time">正在输入...</span>
              </div>
              <div class="message-text">
                <span v-html="streamingRenderedContent"></span>
                <span class="cursor">|</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 底部输入区域 -->
        <div class="input-area">
          <!-- 更多功能面板 -->
          <van-popup 
            :show="showMorePanel" 
            position="bottom" 
            round 
            :style="morePanelStyle" 
            close-on-click-overlay
            @click-overlay="showMorePanel = false"
          >
            <div class="more-panel">
              <van-grid :column-num="4" :border="false">
                <van-grid-item icon="photo-o" text="图片" @click="handleUpload('image')" />
                <van-grid-item icon="description-o" text="文件" @click="handleUpload('file')" />
                <van-grid-item icon="video-o" text="视频" @click="handleUpload('video')" />
                <van-grid-item icon="service-o" text="音频" @click="handleUpload('audio')" />
              </van-grid>
            </div>
          </van-popup>

          <!-- 文件上传对话框 -->
          <van-dialog 
            v-model:show="showUploadDialog" 
            :title="uploadTitle" 
            show-cancel-button 
            @confirm="handleFileConfirm"
            class="upload-dialog"
          >
            <div class="uploader-container">
              <van-uploader 
                v-model="fileList" 
                :after-read="afterRead" 
                :max-count="1" 
                :accept="uploadAccept"
                :preview-image="false"
              >
                <!-- 自定义上传区域 -->
                <div class="custom-uploader">
                  <van-icon :name="uploadIcon" size="48" :color="iconColor" />
                  <div class="upload-text">{{ uploadHint }}</div>
                </div>
              </van-uploader>

              <!-- 显示已选文件信息 -->
              <div v-if="fileList.length > 0" class="file-info">
                <van-icon name="description" size="20" />
                <span class="file-name">{{ fileList[0].file.name }}</span>
                <span class="file-size">({{ formatFileSize(fileList[0].file.size) }})</span>
              </div>
            </div>
          </van-dialog>

          <div class="input-box">
            <van-button 
              round 
              size="small" 
              class="more-btn" 
              @click="toggleMorePanel"
              plain
            >
              <van-icon name="add-o" size="18" />
            </van-button>

            <div class="input-field-container" :class="{ 'has-scroll': shouldScroll }">
              <van-field 
                v-model="userInput" 
                rows="1" 
                type="textarea" 
                placeholder="请输入法律问题..." 
                class="input-field"
                @keyup.enter.exact="sendMessage"
                @input="checkScroll"
                ref="inputField"
                autocomplete="off"
              />
            </div>

            <van-button 
              size="small" 
              type="primary" 
              class="send-btn" 
              @click="sendMessage"
              :disabled="!userInput.trim() || isStreaming"
              :loading="isStreaming"
            >
              <template #icon>
                <van-icon name="send-gift-o" size="16" />
              </template>
            </van-button>

            <van-button 
              round 
              size="small" 
              class="voice-btn" 
              @touchstart="startVoiceInput" 
              @touchend="stopVoiceInput"
              @mousedown="startVoiceInput" 
              @mouseup="stopVoiceInput" 
              :disabled="isStreaming"
              plain
            >
              <van-icon :name="isRecording ? 'pause-circle-o' : 'volume-o'" size="18" />
            </van-button>
          </div>
        </div>

        <!-- 语音输入通知 -->
        <van-notify 
          v-model:show="showVoiceNotify" 
          type="primary" 
          position="bottom" 
          :style="voiceNotifyStyle"
          class="voice-notification"
        >
          <div class="voice-notify">
            <van-icon name="volume-o" size="16" class="pulse-icon" />
            <span>正在语音输入中... (松开结束)</span>
          </div>
        </van-notify>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { showToast } from 'vant';
import { marked } from 'marked';
import DOMPurify from 'dompurify';
import dayjs from 'dayjs';
import aiAvatar from '@/assets/img/robot.png';
import { getCaseById,uploadCaseFile } from '@/api/analysis';
import { getChatDetailsMessages } from '@/api/aichat_history';
import { fetchWithAuth } from '@/utils/request';
import {ElMessage,ElLoading} from 'element-plus'

interface CaseInfo {
  id: number;
  caseName: string;
  caseProcedure: string;
  analysisStatus: string;
  victoryRate: number;
  createTime: string;
}

interface ChatMessageItem {
  role: 'assistant' | 'user'; // 消息发送者类型：AI 或用户
  content: string; // 原始消息文本
  renderedText?: string; // 渲染后的消息（可选，用于富文本或格式化内容）
  time?: number;  // 消息时间（格式化后的字符串，如 "14:30"）
}



const route = useRoute();
const router = useRouter();
const currentChatId = ref<string | null>('');
const caseId = ref<number>();
const caseInfo = ref<CaseInfo>({
  id: 0,
  caseName: '',
  caseProcedure: '',
  analysisStatus: '',
  victoryRate: 0,
  createTime: ''
});

// 聊天相关状态
const messages = ref<ChatMessageItem[]>([
  {
    role: 'assistant',
    content: '您好，我是AI法律顾问小诺，关于这个案件我可以帮您解答什么问题？',
    renderedText: '您好，我是AI法律顾问小诺，关于这个案件我可以帮您解答什么问题？',
  }
]);
const userInput = ref('');
const isStreaming = ref(false);
const streamingRawContent = ref('');
const streamingRenderedContent = ref('');
const streamingBuffer = ref('');
const chatContent = ref<HTMLElement | null>(null);
const shouldScroll = ref(false);
const inputField = ref<HTMLElement>();


// 上传相关状态
const showMorePanel = ref(false); // 是否显示更多面板
const showUploadDialog = ref(false); // 是否显示上传对话框
const fileList = ref<any[]>([]); // 上传文件列表
const uploadType = ref<'image' | 'file' | 'video' | 'audio'>('file'); // 上传类型
const isRecording = ref(false); // 是否正在录音
const showVoiceNotify = ref(false); // 是否显示语音输入通知


// 计算属性
const uploadTitle = computed(() => {
  const titles = {
    image: '上传图片',
    file: '上传文件',
    video: '上传视频',
    audio: '上传音频'
  };
  return titles[uploadType.value];
});

const uploadAccept = computed(() => {
  const accepts = {
    image: 'image/*',
    file: '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt',
    video: 'video/*',
    audio: 'audio/*'
  };
  return accepts[uploadType.value];
});

const uploadIcon = computed(() => {
  const icons = {
    image: 'photo-o',
    file: 'description-o',
    video: 'video-o',
    audio: 'service-o'
  };
  return icons[uploadType.value];
});

const uploadHint = computed(() => {
  const hints = {
    image: '点击上传图片',
    file: '点击上传文件',
    video: '点击上传视频',
    audio: '点击上传音频'
  };
  return hints[uploadType.value];
});

const iconColor = computed(() => {
  return fileList.value.length > 0 ? '#1989fa' : '#969799';
});

const morePanelStyle = computed(() => ({
  height: '25%',
  width: isDesktop.value ? '420px' : '100%',
  left: isDesktop.value ? '50%' : '0',
  transform: isDesktop.value ? 'translateX(-50%)' : 'none',
  maxWidth: '100%'
}));

const voiceNotifyStyle = computed(() => ({
  bottom: isDesktop.value ? '100px' : '180px',
  width: isDesktop.value ? '400px' : 'calc(100% - 20px)',
  left: isDesktop.value ? '50%' : '10px',
  transform: isDesktop.value ? 'translateX(-50%)' : 'none',
  margin: '0 auto',
  borderRadius: '8px'
}));

const isDesktop = computed(() => window.innerWidth >= 768);

// 根据状态获取标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    '已分析': 'success',
    '分析中': 'primary',
    '分析失败': 'warning',
    '未分析': 'danger'
  };
  return statusMap[status] || 'default';
};

// 根据胜率获取进度条颜色
const getVictoryRateColor = (rate: number) => {
  if (rate >= 70) return '#07c160';
  if (rate >= 40) return '#1989fa';
  return '#ee0a24';
};

// 格式化消息时间
const formatMessageTime = (msg: ChatMessageItem) => {
  if (!msg.time) return '';
  return dayjs(msg.time).format('HH:mm');
};

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// Markdown渲染
marked.setOptions({
  breaks: true,
  gfm: true,
});

const renderMarkdown = (markdown: string) => {
  try {
    const rawHtml = marked.parse(markdown);
    return DOMPurify.sanitize(rawHtml);
  } catch (error) {
    console.error('Markdown渲染错误:', error);
    return markdown;
  }
};

/* ============== 历史记录处理模块 ===================== */

/**
 * 发送请求获取历史记录
 * 1. 从router路径参数中获取案件ID caseId
 * 2.根据案件ID获取案件详情(fetchCaseDetail)，包括chatId 
 * 3.（如果有chatId）根据chatId获取历史记录(fetchChatDetailsHistories)，没有则表示第一次对话，
 * 4.(如果没有chatId)不获取历史记录，这个时候传入参数时要传递案件ID，随机生成chatId,让数据库添加chatId
 * 
 */
// 获取当前会话的历史记录
const fetchChatDetailsHistories = async () => {
  try {

    console.log('当前对话currentChatId.value:', currentChatId.value);
    if (!currentChatId.value) {
      console.error('currentChatId 为空');
      return;
    }

    const response = await getChatDetailsMessages(currentChatId.value);

    console.log('获取 上下文历史对话 记录响应data:', response.data);
    const realResponse = response.data;

    // 首先检查响应码是否为200
    if (realResponse.code === 200 && realResponse.data && Array.isArray(realResponse.data)) {
      if(realResponse.data.length>0){
          // 转换数据格式并赋值给chatHistory
      messages.value = realResponse.data.map((item: ChatMessageItem) => ({
        role: item.role, // 添加对话类型, 这里应该是 'chat'
        content: item.content, // 直接使用chatId作为唯一标识
        renderedText: renderMarkdown(item.content), // 渲染Markdown内容
      }))
      // 自动滚动到底部
      scrollToBottom();
      }
    } else {
      console.warn('获取历史记录响应异常:', response);
      // showToast(response.msg || '获取历史记录失败');
      ElMessage({
        message: response.msg || '获取历史记录失败',
        type: 'warning',
      })
    }
  } catch (error) {
    console.error('获取历史记录失败:', error);
    ElMessage({
      message: '获取历史记录失败',
      type: 'warning',
    })
  }
};

// 生成唯一聊天ID
const generateChatId = (): string => {
  return Date.now().toString(36) + Math.random().toString(36).substring(2);
};

// 获取案件详情
const fetchCaseDetail = async (id: number) => {
  try {
    const res = await getCaseById(id);
    currentChatId.value = res.data.data.chatId 
   
  console.log('加载当前对话chatId:', currentChatId.value);
    caseInfo.value = res.data.data;
    console.log('案件详情:', caseInfo.value);
   
  
  } catch (error) {
    console.error('获取案件详情失败:', error);
  }
};
/* ============== 消息发送处理模块 ===================== */
/**
 * 发送用户消息并处理AI的流式响应
 * 1. 校验输入有效性
 * 2. 创建新对话记录（如需要）
 * 3. 发送消息到后端API (sendMessage)
 * 4. 处理流式响应数据 (processStreamData)
 */

// 处理流式数据
const processStreamData = (chunk: string) => {
  try {
    streamingRawContent.value += chunk;
    streamingRenderedContent.value = renderMarkdown(streamingRawContent.value);
    scrollToBottom();
  } catch (error) {
    console.error('处理流式数据时出错:', error);
    showToast('处理流式数据时出错');
  }
};

// 完成流式响应
const completeStreaming = () => {
  isStreaming.value = false;
  const finalRenderedContent = renderMarkdown(streamingRawContent.value);
  messages.value.push({
    role: 'assistant',
    content: streamingRawContent.value,
    renderedText: finalRenderedContent,
    time: Date.now()
  });
  streamingRawContent.value = '';
  streamingRenderedContent.value = '';
  streamingBuffer.value = '';
  scrollToBottom();
  
};

// 处理流式错误
const handleStreamError = () => {
  isStreaming.value = false;
  messages.value.push({
    role: 'assistant',
    content: '抱歉，请求AI服务时出现错误，请稍后再试。',
    renderedText: '抱歉，请求AI服务时出现错误，请稍后再试。',
    time: Date.now()
  });
  streamingRawContent.value = '';
  streamingRenderedContent.value = '';
  streamingBuffer.value = '';
  scrollToBottom();
};

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || isStreaming.value) return;
  
  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: userInput.value,
    renderedText: userInput.value,
    time: Date.now()
  };
  messages.value.push(userMessage);
  userInput.value = '';
  scrollToBottom();
  const userNo = localStorage.getItem("userNo") || "defaultUserNo";
  
  // 初始化流式状态
  isStreaming.value = true;
  streamingRawContent.value = '';
  streamingRenderedContent.value = '';
  streamingBuffer.value = '';
  
  try {
      // 如果没有当前对话ID，创建新对话、并添加到历史记录中
    console.log('对话使用的当前chatId:', currentChatId.value);
    let id = null;
    if (!currentChatId.value) {
      currentChatId.value = generateChatId();
      id= caseId.value;
    }
    console.log('当前的id', id);
    const userNo = localStorage.getItem("userNo") || "defaultUserNo";
    console.log('当前对话chatId:', currentChatId.value);
    console.log('当前用户userNo:', userNo);
    console.log('当前用户输入:', userMessage.content);
    const response = await fetchWithAuth('/api/ai/analysis/chat', {
      method: 'POST',
      body: JSON.stringify({
        id: id,
        userNo: userNo,
        type: 'analysis',
        chatId: currentChatId.value,
        prompt: userMessage.content
      })
    });

    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
    if (!response.body) throw new Error('No response body');

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let receivedLength = 0;

    while (true) {
      const { done, value } = await reader.read();
      if (done) break;

      receivedLength += value.length;
      const chunk = decoder.decode(value, { stream: true });
      processStreamData(chunk);
      await new Promise(resolve => setTimeout(resolve, 50));
    }

    completeStreaming();
     if(caseId.value){
    fetchCaseDetail(caseId.value); // 更新案件详情
  }
  } catch (error) {
    console.error('请求失败:', error);
    showToast('请求失败，请稍后再试');
    handleStreamError();
  }
};

// 检查是否需要滚动
const checkScroll = () => {
  nextTick(() => {
    if (inputField.value) {
      const field = inputField.value.$el.querySelector('textarea');
      if (field) {
        shouldScroll.value = field.scrollHeight > 150;
        if (shouldScroll.value) {
          field.style.height = '150px';
          field.style.overflowY = 'auto';
        } else {
          field.style.height = 'auto';
          field.style.height = field.scrollHeight + 'px';
          field.style.overflowY = 'hidden';
        }
      }
    }
  });
};

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContent.value) {
      chatContent.value.scrollTop = chatContent.value.scrollHeight;
    }
  });
};


/* ============== 其他信息模块 ===================== */
/**
 * 页面切换，文件上传，语音输入，文件读取
 * 
 */

// 返回案件列表
const goBack = () => {
  router.push('/analysis');
};

// 切换更多面板
const toggleMorePanel = () => {
  showMorePanel.value = !showMorePanel.value;
};

// 处理上传类型选择
const handleUpload = (type: 'image' | 'file' | 'video' | 'audio') => {
  uploadType.value = type;
  showUploadDialog.value = true;
  showMorePanel.value = false;
};

// 文件读取后处理
const afterRead = async (file: any) => {
  console.log('当前的caseId', caseId.value);
  console.log('文件已选择:', file);
   const loading = ElLoading.service({
              lock: true,
              text: '文件上传中',
              background: 'rgba(0, 0, 0, 0.7)',
            });
  try { 
    // 调用上传接口
    const response = await uploadCaseFile(caseId.value, file.file);
    // 根据响应处理结果
    if (response.data.code === 200) {
      ElMessage.success('文件上传成功');
    
    } else {
      showToast(response.msg || '文件上传失败');
    }
  } catch (error) {
    console.error('文件上传出错:', error);
    showToast('文件上传出错，请稍后再试');
  } finally {
    // 无论成功失败都重置文件列表
   fileList.value = [];
   loading.close();
    // 0.1秒后执行一次
   setTimeout(() => {
      showUploadDialog.value = false; // 文件上传成功后关闭上传对话框
    }, 100);
      
  }
};

// 确认上传文件
const handleFileConfirm = () => {
  if (fileList.value.length === 0) {
    showToast('请先选择文件');
    return;
  }
  
  const file = fileList.value[0].file;
  showToast(`已选择文件: ${file.name}`);
  fileList.value = [];
  showUploadDialog.value = false;
};

// 开始语音输入
const startVoiceInput = () => {
  if (isStreaming.value) return;
  isRecording.value = true;
  showVoiceNotify.value = true;
};

// 停止语音输入
const stopVoiceInput = () => {
  isRecording.value = false;
  showVoiceNotify.value = false;
  
  if (Math.random() > 0.3) {
    userInput.value = "我想咨询关于这个案件的法律问题";
    showToast('语音输入完成');
  } else {
    showToast('未能识别，请重试');
  }
};

onMounted(async () => {
  caseId.value = Number(route.params.caseId);
  console.log('案件ID:', caseId.value);
  
  if (caseId.value) {
    try {
      await fetchCaseDetail(caseId.value); // 等待案件详情获取完成
      if (currentChatId.value) {
        await fetchChatDetailsHistories(); // 如果有聊天ID，获取聊天历史
      }
    } catch (error) {
      console.error('初始化失败:', error);
    }
  }
  
  scrollToBottom();
});
</script>


<style scoped>
/* ============== 基础布局 ===================== */
.chat-wrapper {
  position: relative;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
  font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 46px - 50px);
  overflow: hidden;
}

/* ============== 案件信息卡片 ===================== */
.case-info-card {
  margin: 12px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  overflow: hidden;
  background: white;
  border: 1px solid #e6e9ed;
}

.case-info-card .van-cell {
  padding: 12px 16px;
  color: #333;
}

.case-info-card .van-cell__title {
  color: #666;
  font-weight: 500;
}

.case-info-card .van-cell__value {
  color: #333;
}

.case-info-card .van-cell:not(:last-child)::after {
  left: 16px;
  right: 16px;
  border-color: #f0f0f0;
}

.victory-rate-text {
  margin-left: 8px;
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

/* ============== 聊天内容区域 ===================== */
.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  background-color: #f5f7fa;
}

.chat-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
  scroll-behavior: smooth;
  display: flex;
  flex-direction: column;
  gap: 16px;
  background-color: #f5f7fa;
}

/* ============== 消息样式 ===================== */
.message {
  display: flex;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message.user {
  justify-content: flex-end;
}

.message.ai {
  justify-content: flex-start;
}

.message-bubble {
  max-width: 80%;
  padding: 12px 16px;
  border-radius: 18px;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  line-height: 1.6;
  font-size: 15px;
  word-wrap: break-word;
}

.message.user .message-bubble {
  background: linear-gradient(135deg, #4a90e2 0%, #5a9cec 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.message.ai .message-bubble {
  background-color: white;
  color: #333;
  border-bottom-left-radius: 4px;
  border: 1px solid #e6e9ed;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
}

.message-header .van-icon,
.message-header .avatar {
  margin-right: 6px;
}

.sender-name {
  font-size: 13px;
  font-weight: 600;
}

.message.user .sender-name {
  color: rgba(255, 255, 255, 0.95);
}

.message.ai .sender-name {
  color: #555;
}

.message-time {
  font-size: 11px;
  margin-left: 8px;
  opacity: 0.8;
}

.message-text {
  word-break: break-word;
}

.message-text p {
  margin: 6px 0;
}

.message-text ul,
.message-text ol {
  padding-left: 22px;
  margin: 8px 0;
}

.message-text li {
  margin-bottom: 5px;
}

.message-text strong {
  font-weight: 600;
}

.message-text em {
  font-style: italic;
}

/* ============== 输入区域 ===================== */
.input-area {
  padding: 12px 16px;
  background-color: white;
  border-top: 1px solid #e6e9ed;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.05);
  position: sticky;
  bottom: 30px;
  z-index: 100;
}

.input-box {
  display: flex;
  align-items: flex-end;
  gap: 10px;
  width: 100%;
}

.input-field-container {
  flex: 1;
  min-height: 44px;
  max-height: 50px;
  border-radius: 22px;
  background-color: #f0f2f5;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  border: 1px solid #e6e9ed;
}

.input-field-container.has-scroll {
  overflow-y: auto;
}

.input-field {
  width: 100%;
  min-height: 44px;
  max-height: 50px;
  padding: 10px 16px;
  border: none;
  outline: none;
  background-color: transparent;
  resize: none;
  font-size: 15px;
  line-height: 1.5;
  box-sizing: border-box;
  color: #333;
}

.input-field::placeholder {
  color: #999;
}

.input-field-container.has-scroll .input-field {
  overflow-y: auto;
}

/* 按钮样式 */
.more-btn,
.send-btn,
.voice-btn {
  height: 44px;
  width: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
  cursor: pointer;
  border: none;
  outline: none;
}

.more-btn {
  background-color: #f0f2f5;
  color: #4a90e2;
}

.more-btn:hover {
  background-color: #e6e9ed;
}

.send-btn {
  background: linear-gradient(135deg, #4a90e2 0%, #5a9cec 100%);
  color: white;
}

.send-btn:disabled {
  background: #b3c7e5;
  opacity: 0.7;
}

.send-btn:hover:not(:disabled) {
  opacity: 0.9;
}

.voice-btn {
  background-color: #f0f2f5;
  color: #4a90e2;
}

.voice-btn:hover {
  background-color: #e6e9ed;
}

/* 更多面板样式 */
.more-panel {
  padding: 16px;
  background-color: white;
}

/* 上传对话框样式 */
.upload-dialog {
  border-radius: 16px;
  overflow: hidden;
  max-width: 90%;
}

.uploader-container {
  padding: 24px;
  text-align: center;
}

.custom-uploader {
  padding: 24px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;
}

.custom-uploader:hover {
  background-color: #f5f7fa;
  border-radius: 8px;
}

.upload-text {
  margin-top: 12px;
  font-size: 14px;
  color: #666;
}

.file-info {
  margin-top: 16px;
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
}

.file-name {
  margin: 0 8px;
  font-size: 14px;
  max-width: 200px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #333;
}

.file-size {
  font-size: 12px;
  color: #999;
}

/* 语音通知样式 */
.voice-notification {
  z-index: 9999;
  background-color: #4a90e2;
  color: white;
}

.voice-notify {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 12px 16px;
  font-size: 14px;
}

.voice-notify .van-icon {
  margin-right: 8px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

/* 滚动条样式 */
.input-field::-webkit-scrollbar {
  width: 6px;
}

.input-field::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.input-field::-webkit-scrollbar-track {
  background-color: transparent;
}

.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb {
  background: #c8c9cc;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: #a6a8ab;
}

/* ============== 动画 ===================== */
.cursor {
  animation: blink 1s infinite;
  color: #4a90e2;
  font-weight: bold;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}

/* ============== 响应式设计 ===================== */
@media (max-width: 767px) {
  .input-area {
    padding-bottom: calc(12px + env(safe-area-inset-bottom));
    bottom: 0px;
  }
  
  .input-field-container {
    max-height: 50px;
  }
  
  .input-field {
    max-height: 50px;
  }
  
  .more-btn,
  .send-btn,
  .voice-btn {
    width: 40px;
    height: 40px;
  }
  
  .case-info-card {
    margin: 8px;
  }
  
  .chat-content {
    padding: 12px;
  }
}

@media (min-width: 768px) {
  .chat-container {
    max-width: 800px;
    margin: 16px auto;
    border-radius: 16px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
    height: calc(100vh - 80px);
    border: 1px solid #e6e9ed;
  }
  
  .input-area {
    border-radius: 0 0 16px 16px;
  padding: 16px;
  box-shadow: none;
  }
  
  .case-info-card {
    margin: 16px;
  }
  
  .message-bubble {
    max-width: 70%;
  }
}

/* 添加一些微妙的过渡效果 */
.van-button,
.van-cell,
.van-uploader,
.van-grid-item {
  transition: all 0.3s ease;
}

.van-button:active {
  transform: scale(0.96);
}

/* 美化标记文本 */
.message-text code {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 90%;
}

.message.user .message-text code {
  background-color: rgba(255, 255, 255, 0.2);
}

.message-text pre {
  background-color: rgba(0, 0, 0, 0.05);
  padding: 10px;
  border-radius: 6px;
  overflow-x: auto;
}

.message.user .message-text pre {
  background-color: rgba(255, 255, 255, 0.15);
}

.message-text blockquote {
  border-left: 3px solid #4a90e2;
  padding-left: 12px;
  margin: 8px 0;
  color: #555;
}

.message.user .message-text blockquote {
  border-left-color: rgba(255, 255, 255, 0.5);
  color: rgba(255, 255, 255, 0.9);
}
</style>